#! /bin/bash

rm -rf ${Titan_path}/FinalModel
mkdir -p ${Titan_path}/FinalModel

for Tumor in `cat ${list_file} | grep -v Tumor | awk -F, '{print $1}' | sort -u`
do
echo ${Tumor}

num=`cat ${Titan_path}/CheckModel/Diploid_lowPurity_chooseModel.tsv ${Titan_path}/CheckModel/HighPloidy_chooseModel.tsv | grep -w ${Tumor} | awk -F'\t' '{print $8}' | awk NF | wc -l`
if [[ ${num} -eq 0 ]]
then
## 使用默认模型
cat ${Titan_path}/optimalClusterSolution/${Tumor}_optimalClusterSolution.txt | awk -F'\t' '{OFS="\t"}{print $1,$2,$3,$6,$8,$9,$10,$11}' \
> ${Titan_path}/FinalModel/${Tumor}_optimalClusterSolution.txt
cp -rf ${Titan_path}/optimalClusterSolution/${Tumor}_titanCNA_result ${Titan_path}/FinalModel/${Tumor}_titanCNA_result
else
## 使用选择的模型
phi=`cat ${Titan_path}/CheckModel/Diploid_lowPurity_chooseModel.tsv ${Titan_path}/CheckModel/HighPloidy_chooseModel.tsv | \
grep -w ${Tumor} | awk -F'\t' '{print $8}'`
cluster=`cat ${Titan_path}/CheckModel/Diploid_lowPurity_chooseModel.tsv ${Titan_path}/CheckModel/HighPloidy_chooseModel.tsv | \
grep -w ${Tumor} | awk -F'\t' '{print $9}' | sed 's/cluster//'`
mkdir -p ${Titan_path}/FinalModel/${Tumor}_titanCNA_result

cp -rf ${Titan_path}/hmm/${Tumor}_titanCNA_ploidy${phi}/${Tumor}_cluster${cluster}/*CNA*pdf \
${Titan_path}/FinalModel/${Tumor}_titanCNA_result/
cp -rf ${Titan_path}/hmm/${Tumor}_titanCNA_ploidy${phi}/${Tumor}_cluster${cluster}/*LOH*pdf \
${Titan_path}/FinalModel/${Tumor}_titanCNA_result/
cp -rf ${Titan_path}/hmm/${Tumor}_titanCNA_ploidy${phi}/${Tumor}_cluster${cluster}/*CF.pdf \
${Titan_path}/FinalModel/${Tumor}_titanCNA_result/

cp -rf ${Titan_path}/hmm/${Tumor}_titanCNA_ploidy${phi}/${Tumor}_cluster${cluster}.*txt \
${Titan_path}/FinalModel/${Tumor}_titanCNA_result/
cp -rf ${Titan_path}/hmm/${Tumor}_titanCNA_ploidy${phi}/${Tumor}_cluster${cluster}.*seg \
${Titan_path}/FinalModel/${Tumor}_titanCNA_result/

cat ${Titan_path}/allModel/All_allModel_params.tsv | head -1 > ${Titan_path}/FinalModel/${Tumor}_optimalClusterSolution.txt
cat ${Titan_path}/allModel/All_allModel_params.tsv  | grep -w ${Tumor} | awk -F'\t' '{if($2~cluster && $1~phi )print}' phi=${phi} cluster=${cluster} \
>> ${Titan_path}/FinalModel/${Tumor}_optimalClusterSolution.txt
fi
done